<template>
  <cu-layout :bgStyle="{ color: actBgColor }" :class="[showTip ? 'fixed' : '']" :navProp="{ placeholder: true, isOpacity: false }">
    <view :class="[`${prefixCls}-student-certification-container`]">
      <view class="activity-body">
        <view class="activity-body-card">
          <view class="card-content">
            <view class="tab">
              <view
                class="tab-l"
                v-for="(item, i) in tabList"
                :key="i"
                :class="[graduationForm.graduation_type == item.name ? 'selected' : '']"
                @click="choseCertificate(item.name)"
              >
                <view>
                  <text>{{ item.name }}</text>
                  <text></text>
                </view>
              </view>
            </view>
            <view class="card-content-item">
              <view @click="datetimeClick">
                <uv-input border="bottom" placeholder="请选择毕业时间" inputAlign="right" disabled disabledColor="white" color="#333333" v-model="graduation_time_text">
                  <template v-slot:prefix>
                    <uv-text text="毕业时间" size="13" margin="10rpx 0"></uv-text>
                  </template>
                  <template v-slot:suffix>
                    <uv-icon name="arrow-right"></uv-icon>
                  </template>
                </uv-input>
              </view>
              <uv-input border="bottom" placeholder="请输入姓名" inputAlign="right" disabledColor="white" color="#333333" v-model="graduationForm.name">
                <template v-slot:prefix>
                  <uv-text text="姓名" size="13" margin="10rpx 0"></uv-text>
                </template>
              </uv-input>
              <uv-input border="bottom" placeholder="请输入身份证" inputAlign="right" disabledColor="white" color="#333333" v-model="graduationForm.card_num">
                <template v-slot:prefix>
                  <uv-text text="身份证" size="13" margin="10rpx 0"></uv-text>
                </template>
              </uv-input>
              <view @click="handleChangeinstitutionType">
                <uv-input border="bottom" placeholder="请选择学历" inputAlign="right" disabled disabledColor="white" color="#333333" v-model="graduationForm.education">
                  <template v-slot:prefix>
                    <uv-text text="学历" size="13" margin="10rpx 0"></uv-text>
                  </template>
                  <template v-slot:suffix>
                    <uv-icon name="arrow-right"></uv-icon>
                  </template>
                </uv-input>
              </view>
              <uv-input border="bottom" placeholder="请输入校院名称" inputAlign="right" disabledColor="white" color="#333333" v-model="graduationForm.institutions">
                <template v-slot:prefix>
                  <uv-text text="校院名称" size="13" margin="10rpx 0"></uv-text>
                </template>
              </uv-input>
              <view>
                <view class="content__title content__title--second">学生证明</view>
                <view class="content__tips content__tips--first">请上传学生证及在校生凭证</view>
                <cu-uploader v-model="certificate_image" :limit="1"></cu-uploader>
                <view class="content__tips content__tips--second">
                  <view>温馨提示：请使用填写的身份证签约合同，否则无法享受在校生权益， 认证成功后将无法修改。</view>
                </view>
              </view>
              <view class="agreement">
                <text class="click-area" @click="agree()">
                  <text class="icon" :class="{ selected: graduationForm.agree }"></text>
                  <text class="note">我已阅读并同意</text>
                </text>
                <text class="agreement-text" @click="authorizationAgreement()">《授权协议》</text>
              </view>
            </view>
            <view class="subBtn">
              <uv-button
                @click="submit"
                text="提交认证"
                :disabled="!highLight"
                :customStyle="{ 'box-shadow': '0px 8rpx 20rpx 0rpx rgba(254, 146, 22, 0.3)', 'font-size': '16px', 'line-height': '48px' }"
                color="linear-gradient( 90deg, #FFCC15 0%, #FF8710 100%)"
                shape="circle"
              ></uv-button>
            </view>
          </view>
        </view>
      </view>
      <!-- 活动规则 -->
      <view class="rule-tips" :style="{ top: `${$Platform.device.safeAreaInsets.top + 44 + 20}px` }" @click="openRulePopup">活动规则</view>
      <uv-datetime-picker
        ref="datetimePicker"
        :minDate="minDate"
        :maxDate="maxDate"
        v-model="graduationForm.graduation_date"
        mode="year-month"
        @confirm="pickerChangeGraduationTime"
      >
      </uv-datetime-picker>
      <!-- 提交返回结果 -->
      <ResultPage v-if="showTip" :tipData="tipData" @clickTipBtn="clickTipBtn" />
      <ActivityRule ref="activityRulePopup" :ruleInfo="actRule" />
      <!-- 学历类型 -->
      <uv-picker ref="institutionTypePickerRef" :columns="institutionsTypeColumns" @confirm="institutionTypeConfirm"></uv-picker>
    </view>
  </cu-layout>
</template>
<script>
import { mapGetters } from 'vuex'
import ResultPage from './components/result-page.vue'
import ActivityRule from './components/activity-rule.vue'
import { getCertificationInfo, commitCertification } from './api'
import { isEmpty } from '@/common/helper/is'
import { institutionsTypeColumns } from '@/common/enums/signingReservationEnum'
export default {
  name: 'graduationCertificationDetail',
  components: { ResultPage, ActivityRule },
  props: {},
  data() {
    return {
      institutionsTypeColumns,
      actRule: {
        title: '活动规则',
        content: '',
      },
      minDate: new Date('2022-02').getTime(),
      maxDate: new Date('2022-12').getTime(),
      tabList: [
        {
          name: '大陆高校在校生',
        },
        {
          name: '港澳台及海外留学生',
        },
      ],
      datetimePickerShow: false,
      graduate: {},
      activity: {},
      certificate_image: [],
      graduationForm: {
        institutions: '',
        education: '',
        graduation_type: '大陆高校在校生',
        graduation_date: '',
        graduation_time: '',
        name: '',
        card_num: '',
        agree: false,
        certificate_url: '',
      },
      graduation_time_text: '', //页面回显
      showTip: false,
      tipData: {},
      options: {},
    }
  },
  // 侦听属性
  watch: {},
  // 计算属性
  computed: {
    ...mapGetters(['isLogin', 'userInfo']),
    actBgImage() {
      return `url(${this.graduate?.top_image || CDN('/customer/static/images/student/student_bg@2x.png')})  no-repeat top center / 100% auto`
    },
    actBgColor() {
      return '#0DA199'
    },
    highLight() {
      return (
        this.certificate_image.length &&
        this.graduationForm.institutions != '' &&
        this.graduationForm.education != '' &&
        this.graduationForm.graduation_date != '' &&
        this.graduationForm.name != '' &&
        this.graduationForm.card_num != '' &&
        this.graduationForm.agree
      )
    },
  },
  // 监听页面加载，该钩子被调用时data,computed,function,watch,props,slots已设置完成
  async onLoad(options) {
    console.log('🚀 ~ onLoad student-certificationDetail~ options:', options)
    this.options.id = options.id || ''
    this.getPageData()
  },
  // 监听页面显示，页面每次出现在屏幕上都触发
  onShow() {},
  // 监听页面初次渲染完成，此时组件已挂载完成
  onReady() {},
  // 下拉刷新
  onPullDownRefresh() {},
  // 加载更多
  onReachBottom() {},

  created() {},
  mounted() {},
  destroyed() {},
  methods: {
    async getPageData() {
      // 获取活动详情
      this.getData()
    },
    handleChangeinstitutionType() {
      this.$refs['institutionTypePickerRef'].open()
    },
    institutionTypeConfirm(e) {
      this.graduationForm.education = e.value[0]
    },
    // 显示规则
    openRulePopup() {
      this.$refs.activityRulePopup.open()
    },
    datetimeClick() {
      this.$refs.datetimePicker.open()
    },
    pickerChangeGraduationTime(e) {
      let timestamp = e.value
      this.graduationForm.graduation_date = timestamp
      this.graduationForm.graduation_time = this.formatDate(timestamp).num_time
      this.graduation_time_text = this.formatDate(timestamp).time
    },
    formatDate(timestamp) {
      const date = new Date(timestamp)
      const year = date.getFullYear() // 获取年份
      const month = (date.getMonth() + 1).toString().padStart(2, '0') // 获取月份并补充0
      const day = date.getDate().toString().padStart(2, '0') // 获取日期并补充0
      return {
        time: `${year}年${month}月`,
        num_time: `${year}-${month}`,
      }
    },
    clickTipBtn() {
      if (this.tipData.type == '认证成功') {
        this.$ROUTE.go('/pages/subpackage/benefits-list/index')
      }
      if (this.tipData.type == '认证未通过' || this.tipData.type == '未生成学籍报告' || this.tipData.type == '提交失败') {
        this.showTip = false
        this.getData(true) // 传入参数是为了返回修改重新拉数据，并且不再弹出提示页面
      }
    },
    async submit() {
      this.graduationForm.certificate_url = this.certificate_image
        .map((item) => {
          return item.url
        })
        .join('')
      console.log(this.graduationForm, 'this.graduationForm')
      if (!this.highLight) return
      try {
        let resData = await commitCertification(this.graduationForm)
        if (resData.errcode == 0) {
          this.initTip(resData.data)
          return false
        }
      } catch (e) {
        let tipData = {
          audit_status: '提交失败',
          status_hint: 'Oops，提交失败了~',
          remark: '网络好像有些问题，重新提交试试',
        }
        this.initTip(tipData)
      }
    },
    choseCertificate(type) {
      this.graduationForm.graduation_type = type
    },
    agree() {
      this.graduationForm.agree = !this.graduationForm.agree
    },
    authorizationAgreement() {
      this.$ROUTE.go('/pages/subpackage/privacy-policy/privacy-detail?title=在校生授权协议&subtitle=student_authorization_agreement')
    },
    initTip(params) {
      this.tipData.title = params.status_hint
      this.tipData.smTitle = params.remark
      this.tipData.type = params.audit_status
      switch (params.audit_status) {
        case '未生成学籍报告':
          this.tipData.img = CDN('/customer/static/images/graduation/fail.png')
          this.tipData.btnText = '返回修改'
          this.showTip = true
          break
        case '待审核':
          this.tipData.img = CDN('/customer/static/images/graduation/wait.png')
          this.tipData.btnText = ''
          this.showTip = true
          break
        case '认证未通过':
          this.tipData.img = CDN('/customer/static/images/graduation/fail.png')
          this.tipData.btnText = '返回修改'
          this.showTip = true
          break
        case '认证失败':
          this.tipData.img = CDN('/customer/static/images/graduation/fail.png')
          this.tipData.btnText = ''
          this.showTip = true
          break
        case '认证成功':
          this.tipData.img = CDN('/customer/static/images/graduation/success.png')
          this.tipData.btnText = '查看我的权益卡片'
          this.showTip = true
          break
        case '提交失败':
          this.tipData.img = CDN('/customer/static/images/graduation/fail.png')
          this.tipData.btnText = '返回重新提交'
          this.showTip = true
          break
        case '取消认证':
          this.tipData.img = CDN('/customer/static/images/graduation/fail.png')
          this.tipData.btnText = ''
          this.showTip = true
          break
      }
    },
    async getData(flag) {
      let { data } = await getCertificationInfo({ graduate_id: this.options.id })
      this.graduate = data.graduate || {}
      this.activity = data.activity
      this.minDate = new Date(this.activity.graduation_time_start).getTime()
      this.maxDate = new Date(this.activity.graduation_time_end).getTime()
      this.actRule.content = this.activity.rule
      this.graduationForm.cc_graduate_id = this.activity.marketing_activity_id
      if (!isEmpty(this.graduate)) {
        if (!flag) {
          let tipData = {
            audit_status: this.graduate.audit_status,
            status_hint: this.graduate.status_hint,
            remark: this.graduate.remark,
          }
          this.initTip(tipData)
          return false
        }
        this.graduationForm.graduation_time = this.graduate.original_graduation_time
        this.graduationForm.graduation_date = new Date(this.graduate.original_graduation_time).getTime()
        this.graduation_time_text = this.graduate.graduation_time
        this.graduationForm.name = this.graduate.name
        this.graduationForm.card_num = this.graduate.card_num
        this.graduationForm.agree = true
        this.graduation.institutions = this.graduate.institutions
        this.graduation.education = this.graduate.education
        this.certificate_image = this.graduate.certificate_url?.split().map((item) => {
          return {
            url: item,
          }
        })
      } else {
        this.graduationForm.graduation_type = '大陆高校在校生'
      }
    },
  },
}
</script>

<style lang="scss" scoped>
.fixed {
  position: fixed;
}
.#{prefixCls('student-certification-container')} {
  position: relative;
  padding: 40rpx 30rpx 40rpx;
  background: v-bind(actBgImage);
  min-height: 100vh;
  .activity-body {
    position: relative;
    margin-top: 684rpx;
    .activity-body-card {
      margin-bottom: 60rpx;
      padding: 60rpx 24rpx 24rpx;
      background: #fff;
      border-radius: 24rpx;
      .card-content {
        .tab {
          margin-bottom: 40rpx;
          @include flex-center;
          .tab-l {
            width: 50%;
            @include flex;
            justify-content: center;
            view {
              position: relative;
              text:nth-child(1) {
                color: #999999;
                font-size: 30rpx;
                position: relative;
                z-index: 1;
              }
              text:nth-child(2) {
                position: absolute;
                z-index: 0;
                bottom: 0;
                left: -10rpx;
                display: inline-block;
                width: 100%;
                padding: 0 10rpx;
                background: #a3d4ff;
                height: 20rpx;
                opacity: 0;
                border-radius: 10rpx;
              }
            }
            &.selected {
              view {
                text:nth-child(1) {
                  color: #333333;
                  font-weight: bold;
                }
                text:nth-child(2) {
                  opacity: 1;
                }
              }
            }
          }
        }
        .card-content-item {
          .content__title--first {
            margin-bottom: 20rpx;
          }
          .content__tips {
            font-size: 24rpx;
            line-height: 32rpx;
            color: #999999;
          }
          .content__tips--first {
            margin: 12rpx 0 20rpx 0;
          }
          .content__tips--second {
            margin-top: 20rpx;
            font-size: 20rpx;
          }
          .content__title--second {
            margin-top: 30rpx;
          }
        }
        .agreement {
          margin-top: 20rpx;
          .click-area {
            text {
              display: inline-block;
            }
            text.icon {
              width: 26rpx;
              height: 26rpx;
              border: 2rpx solid #cccccc;
              border-radius: 50%;
              box-sizing: border-box;
              margin-bottom: -6rpx;
              &.selected {
                width: 26rpx;
                height: 26rpx;
                border: none;
                background-image: #{cdn('/customer/static/images/graduation/ok.png')};
                background-size: cover;
              }
            }
            text.note {
              color: #999999;
              font-size: 24rpx;
              margin-left: 10rpx;
            }
          }
          .agreement-text {
            font-size: 24rpx;
            color: $uv-primary;
          }
        }
      }
    }
  }
  .subBtn {
    margin: 40rpx 0 20rpx 0;
  }
  .rule-tips {
    width: 132rpx;
    box-sizing: border-box;
    height: 48rpx;
    position: fixed;
    right: 0;
    padding: 0 16rpx;
    background: rgba($color: #000000, $alpha: 0.2);
    border-top-left-radius: 240rpx;
    border-bottom-left-radius: 240rpx;
    line-height: 48rpx;
    font-size: 24rpx;
    color: #fff;
    z-index: 98;
  }
}
</style>
